package com.mzl.lal4cloud.lxw4rf.service.contract.http.okhttp;


import com.mzl.lal4cloud.lxw4rf.service.contract.exception.ErrorException;
import com.mzl.lal4cloud.lxw4rf.service.contract.http.RequestHttp;
import com.mzl.lal4cloud.lxw4rf.service.contract.http.SimpleGetRequestExecutor;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * .
 *
 * @author ecoolper
 * @date 2017/5/4
 */
public class OkHttpSimpleGetRequestExecutor extends SimpleGetRequestExecutor<OkHttpClient, OkHttpProxyInfo> {
    public OkHttpSimpleGetRequestExecutor(RequestHttp requestHttp) {
        super(requestHttp);
    }

    @Override
    public String execute(String uri, String queryParam) throws ErrorException, IOException {
        if (!StringUtils.isBlank(queryParam)) {
            if (uri.indexOf('?') == -1) {
                uri += '?';
            }
            uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
        }

        //得到httpClient
        OkHttpClient client = requestHttp.getRequestHttpClient();

        final Request.Builder requestBuilder = new Request
                .Builder()
                .url(uri)
                .headers(getHeaders(uri, queryParam));

        Response response = client.newCall(requestBuilder.build()).execute();
        return this.handleResponse(response);
    }

}
